package com.eryos.android.cigarettecounter;

/**
 * Project :  CigaretteCounter
 * Author :   Olivier Combe 
 * URL :      http://eryos.fr/CigaretteCounter/
 *
 * Copyright (C) 2011 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

import java.io.IOException;
import java.util.ArrayList;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.eryos.android.cigarettecounter.io.DataExporter;
import com.eryos.android.cigarettecounter.io.DataImporter;
import com.eryos.android.cigarettecounter.io.Preferences;
import com.eryos.android.cigarettecounter.io.RestClient;
import com.eryos.android.cigarettecounter.io.RestClient.RequestMethod;

public class ConfigActivity extends RootActivity {

	private static final String LOG_TAG = "ConfigActivity";

	/** *************** UI Elements *************** **/	
	private Button cleanDataButton; 
	private Button insertButton; 
	private Button exportButton; 
	private Button importButton; 
	private Button invalidDateButton; 
	private Button validButton; 
	//	private DatePicker invalidDatePicker;
	private EditText priceInputField;
	private TextView marketLastVersionField;
	private Button marketUpdateButton; 

	private Spinner boxSpinner;
	private ArrayAdapter<CharSequence> adapter;

	/** *************** Instance Variables *************** **/
	private int boxSize = -1;
	private float boxPrice = -1l;
	private float cigPrice = -1l;

	/* Android Market Information */
	private String marketLastVersion;
	private int    marketLastVersionCode;
	private String marketPackageName;
	private String marketID;


	// Need handler for callbacks to the UI thread
	final Handler mHandler = new Handler();

	// Create runnable for posting
	Runnable mInitialLoadOk = new Runnable() {
		public void run() {
			insertDataComplete();
		}
	};

	Runnable mImportOk = new Runnable() {
		public void run() {
			insertDataComplete();
		}
	};

	Runnable mExportOk = new Runnable() {
		public void run() {
			insertDataComplete();
		}
	};

	Runnable mDeleteOk = new Runnable() {
		public void run() {
			insertDataComplete();
		}
	};

	/** Called when the activity is first created. */
	/*@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }*/

	public void initUI(){    	
		setContentView(R.layout.config);

		cleanDataButton 	= (Button) findViewById(R.id.config_data_delete_button);
		insertButton 		= (Button) findViewById(R.id.config_data_insert_button);
		invalidDateButton 	= (Button) findViewById(R.id.config_data_invalid_button);
		exportButton 		= (Button) findViewById(R.id.config_data_export_button);
		validButton 		= (Button) findViewById(R.id.config_cost_valid_button);
		importButton 		= (Button) findViewById(R.id.config_data_import_button);
		boxSpinner 			= (Spinner) findViewById(R.id.config_cost_size_value);
		priceInputField		= (EditText) findViewById(R.id.config_cost_price_value);
		marketLastVersionField= (TextView) findViewById(R.id.config_app_last_version);
		marketUpdateButton	= (Button) findViewById(R.id.config_app_update_button); 
		adapter = ArrayAdapter.createFromResource( this, R.array.sizes_array, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		boxSpinner.setAdapter(adapter);
	}

	public void initValues(){    	

	/*	Preferences pref = new Preferences(getSharedPreferences(PREFS_NAME, 0));
		pref.readParamFromFile();
		boxPrice = pref.getBoxPrice();
		boxSize = pref.getBoxSize();
		
		Log.w(getLocalClassName(), "[initValues] Load 1 Config Price : "+boxPrice+" Size : "+boxSize);
*/
		marketLastVersionCode = -1;
		marketLastVersion = "NA";
		marketPackageName = null;
		marketID = null;

		/* Retrieve last version deployed on Android Market */
		RestClient client = new RestClient("http://eryos-androidmarketinformation.appspot.com/androidmarketinformation");
		client.AddParam("appli", "com.eryos.android.cigarettecounter");

		try {
			client.Execute(RequestMethod.GET);

			String response = client.getResponse();
			String[] responseLines = response.split("\n");
			for ( String line : responseLines){
				String[] elements = line.split(":");
				if ( elements[0] != null && elements.length == 2 && elements[0].equalsIgnoreCase("Version"))
					marketLastVersion = elements[1];
				else if( elements[0] != null && elements.length == 2 && elements[0].equalsIgnoreCase("Package"))
					marketPackageName = elements[1];
				else if( elements[0] != null && elements.length == 2 && elements[0].equalsIgnoreCase("ID"))
					marketID = elements[1];
				else if( elements[0] != null && elements.length == 2 && elements[0].equalsIgnoreCase("VersionCode"))
					marketLastVersionCode = new Integer(elements[1]);
			}
		}
		catch (Exception e) {
			Log.e(LOG_TAG, "initValues(MArket)", e);
		}
	}

	/**
	 * Save the current price and box size values
	 */
	public void saveConfig(){
		
		Log.i(getLocalClassName(), "Save Config");
		Preferences pref = new Preferences(getSharedPreferences(PREFS_NAME, 0));

		try {
			pref.setBoxSize(boxSize);
			Float boxPrice = new Float(priceInputField.getText().toString());
			pref.setBoxPrice(boxPrice);

			cigPrice = boxPrice / boxSize;
			Log.d(getLocalClassName(), "Cigarette Price: "+cigPrice);
			pref.setCigarettePrice(cigPrice);
			Log.d(getLocalClassName(), "[saveConfig] Save Config Price : "+boxPrice+" Size : "+boxSize);

			pref.storeParamToFile();
		} catch (Exception e) {
			Log.w(getLocalClassName(), "Save Config Price : "+boxPrice+" Size : "+boxSize);
			Log.w(getLocalClassName(), "Save Config", e);
		}
		
		Preferences pref2 = new Preferences(getSharedPreferences(PREFS_NAME, 0));
		pref2.readParamFromFile();
		boxPrice = pref2.getBoxPrice();
		boxSize = pref2.getBoxSize();
		
		Log.d(getLocalClassName(), "[saveConfig] Load 2 Config Price : "+boxPrice+" Size : "+boxSize);

		hideWaitingMessage(R.string.config_valid_OK);
	}

	/**
	 * Delete all data from DB
	 */
	public void deleteData(){
		Log.i(getLocalClassName(), "Delete All Data");
		db.deleteAll();
	}

	public void deleteDataComplete(){
		hideWaitingMessage(R.string.config_delete_OK);
	}

	/**
	 * Insert random data for the last 6 months
	 */
	public void insertData(){
		Log.i(getLocalClassName(), "Insert Random Data");
		db.insertRandomData(cigPrice);
	}

	public void insertDataComplete(){
		hideWaitingMessage(R.string.config_insert_OK);
	}

	/**
	 * Invalid the date selected with the date picker
	 */
	public void invalidDate(){
		Log.i(getLocalClassName(), "Invalid a date");
		/*int day = invalidDatePicker.getDayOfMonth();
    	int month = invalidDatePicker.getMonth()+1;
    	int year = invalidDatePicker.getYear();*/
		// TODO
		//    	db.invalidDate(day, month, year);

		hideWaitingMessage(R.string.config_invalid_OK);
	}

	/**
	 * Export data to SD card ( Public Downloads folder )
	 */
	public void exportData(){
		Log.i(getLocalClassName(), "Export data to SD");
		DataExporter export = new DataExporter(SDCARD_NAME);

		try {
			if ( export.openStream() ){

				ArrayList<String> data = db.exportData();

				for (String line : data ){
					export.writeDataToExternalFile(line+"\n");

				}
				export.closeStream();
			}
		} catch (IOException e) {
			Log.e(getLocalClassName(), "Export data to SD", e);
			hideWaitingMessage(R.string.config_export_NOK);
		}    	
	}

	public void exportDataComplete(){
		hideWaitingMessage(R.string.config_export_OK);
	}

	/**
	 * Import data from SD Card file
	 */
	public void importData(){
		Log.i(getLocalClassName(), "Import data from SD");
		DataImporter importer = new DataImporter(SDCARD_NAME);

		try {
			if ( importer.openStream() ){

				ArrayList<String> data = importer.readDataFromExternalFile();
				db.importData(data);

				importer.closeStream();
			}
		} catch (IOException e) {
			e.printStackTrace();
			hideWaitingMessage(R.string.config_import_NOK);
		}
	}

	public void importDataComplete(){
		hideWaitingMessage(R.string.config_import_OK);
	}

	/**
	 * 
	 */
	public void updateUI(){
		
		Preferences pref = new Preferences(getSharedPreferences(PREFS_NAME, 0));
		pref.readParamFromFile();
		boxPrice = pref.getBoxPrice();
		boxSize = pref.getBoxSize();
		
		int position = 0;

		/* Update Spinner position */
		/*for ( int i = 0 ; i < adapter.getCount(); i++ ){
			int valueList = Integer.parseInt(adapter.getItem(i).toString());
			if ( valueList == boxSize  ){
				position = i;
				break;
			}
		}*/
		position = adapter.getPosition(String.valueOf(boxSize));
		
		if ( boxPrice != -1l )
			priceInputField.setText(boxPrice+"");

		Log.d(getLocalClassName(), "[updateUI] Size : "+boxSize+" Position : "+position);
		if ( boxSize != -1 && boxSpinner != null ){
			boxSpinner.setSelection(position);
		}

		/* Refresh informations from Android Market */
		marketLastVersionField.setText(marketLastVersion);
		if (marketID != null ){
			try {
				PackageInfo packageInfo = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);                           
				int currentVersionCode = packageInfo.versionCode;

				if( currentVersionCode < marketLastVersionCode )				
					marketUpdateButton.setEnabled(true);

			} catch (NameNotFoundException e) {
				Log.e(LOG_TAG, "updateUI - VersionCode", e);
			}
		}
	}

	/**
	 * 
	 */
	public void initHandlers() {

		boxSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { 
				String res = parent.getItemAtPosition(pos).toString(); 
				boxSize = new Integer(res);
			} 

			public void onNothingSelected(AdapterView<?> parent) { } 
		});            

		validButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showWaitingMessage();
				saveConfig();
			}
		});

		cleanDataButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showWaitingMessage();            	
				Thread t = new Thread() {
					public void run() {
						deleteData();
						mHandler.post(mDeleteOk);
					}
				};
				t.start();
			}
		});

		exportButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showWaitingMessage();
				Thread t = new Thread() {
					public void run() {
						exportData();
						mHandler.post(mExportOk);
					}
				};
				t.start();
			}
		});

		importButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showWaitingMessage();
				Thread t = new Thread() {
					public void run() {
						importData();
						mHandler.post(mImportOk);
					}
				};
				t.start();
			}
		});

		insertButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showWaitingMessage();
				Thread t = new Thread() {
					public void run() {
						insertData();
						mHandler.post(mInitialLoadOk);
					}
				};
				t.start();
			}
		});

		invalidDateButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showWaitingMessage();
				invalidDate();
			}
		});
		
		marketUpdateButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
//				Link to Market : 
				String uri = "http://market.android.com/details?id=" + marketPackageName; 
				Log.d(LOG_TAG, "uri: " + uri); 
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); 
				ConfigActivity.this.startActivity(intent); 
			}
		});		
	}
}
